﻿using Futuret.Core.Extensions;
using Futuret.Core.Futuret;
using Futuret.Core.Futuret.Interface;
using Microsoft.AspNetCore.Builder;

namespace Future.Shared.Core.Extensions;

/// <summary>
///     Author: Riva
///     Date: 2023/7/11 14:16
///     Description: ApplicationBuilderExtension扩展
/// </summary>
public static class ApplicationBuilderExtension
{
    /// <summary>
    ///     统一注册WebApi通用中间件
    /// </summary>
    /// <param name="app"></param>
    /// <returns></returns>
    public static IApplicationBuilder UseAdd(this IApplicationBuilder app)
    {
        var serviceInfo = AppInfo.GetInstance();
        AppInfo.AddElement(x => { x.rootServices = app.ApplicationServices; });

        var middlewareRegistarType = serviceInfo.AllTypes
            .FirstOrDefault(m => m.IsAssignableTo(typeof(IMiddlewareRegistrar)) && m.IsNotAbstractClass(true));

        if (middlewareRegistarType is null)
            throw new NullReferenceException(nameof(IMiddlewareRegistrar));

        if (Activator.CreateInstance(middlewareRegistarType, app) is not IMiddlewareRegistrar middlewareRegistar)
            throw new NullReferenceException(nameof(middlewareRegistar));

        middlewareRegistar.UseAdd();
        return app;
    }
}